package login

import (
	"appengine"
	"appengine/user"
	"fmt"
	"net/http"
)

func Do(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	u := user.Current(c)
	if u == nil {
		url, err := user.LoginURL(c, r.URL.String())
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.Header().Set("Location", url)
		w.WriteHeader(http.StatusFound)
		return
	}
	fmt.Fprint(w, "You are now logged in as ", u, ", ", u.ID)
	if user.IsAdmin(c) {
		fmt.Fprint(w, "(Admin)")
	} else {
		fmt.Fprint(w, "(not Admin)")
	}
}

func Check(r *http.Request) (bool, string) {
	c := appengine.NewContext(r)
	u := user.Current(c)
	if u == nil {
		return false, "not logged in"
	}
	if !user.IsAdmin(c) {
		return false, "not Admin"
	}
	if !isAuth(u) {
		return false, "not Auth user"
	}
	return true, ""
}
